package com.gzsxy.lesson01.udp.thread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 接收端
 */
public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;

    public TalkReceive(int port, String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            //设置接收端的端口
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {


        //不断接收
        while (true) {
            try {
                //准备接收包裹
                byte[] container = new byte[1024];

                //得到数据的存储
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet); //阻塞式接收包裹

                //获取数据
                byte[] data = packet.getData();
                //字节码转为string
                String receiveData = new String(data, 0, data.length);

                //打印数据
                System.out.println(msgFrom + ":" + receiveData);
                //如果接收数据字符串有bye 则结束接收
                if (receiveData.equals("bye")) {
                    //断开连接，bye
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        socket.close();
    }
}
